'use client';

import { createContext, useContext, useContextSelector } from 'use-context-selector';
import { useState } from 'react';
import type { Model, ModelProvider } from '@/app/components/header/account-setting/model-provider-page/declarations';
import type { RETRIEVE_METHOD } from '@/types/app';
import { Plan, type UsagePlanInfo } from '@/app/components/billing/type';
import { defaultPlan } from '@/app/components/billing/config';

type ProviderContextState = {
  modelProviders: ModelProvider[];
  textGenerationModelList: Model[];
  supportRetrievalMethods: RETRIEVE_METHOD[];
  isAPIKeySet: boolean;
  plan: {
    type: Plan;
    usage: UsagePlanInfo;
    total: UsagePlanInfo;
  };
  isFetchedPlan: boolean;
  enableBilling: boolean;
  onPlanInfoChanged: () => void;
  enableReplaceWebAppLogo: boolean;
  modelLoadBalancingEnabled: boolean;
  datasetOperatorEnabled: boolean;
};
const ProviderContext = createContext<ProviderContextState>({
  modelProviders: [],
  textGenerationModelList: [],
  supportRetrievalMethods: [],
  isAPIKeySet: true,
  plan: {
    type: Plan.sandbox,
    usage: {
      vectorSpace: 32,
      buildApps: 12,
      teamMembers: 1,
      annotatedResponse: 1,
      documentsUploadQuota: 50,
    },
    total: {
      vectorSpace: 200,
      buildApps: 50,
      teamMembers: 1,
      annotatedResponse: 10,
      documentsUploadQuota: 500,
    },
  },
  isFetchedPlan: false,
  enableBilling: false,
  onPlanInfoChanged: () => {},
  enableReplaceWebAppLogo: false,
  modelLoadBalancingEnabled: false,
  datasetOperatorEnabled: false,
});

export const useProviderContext = () => useContext(ProviderContext);

// Adding a dangling comma to avoid the generic parsing issue in tsx, see:
// https://github.com/microsoft/TypeScript/issues/15713
export const useProviderContextSelector = <T,>(selector: (state: ProviderContextState) => T): T =>
  useContextSelector(ProviderContext, selector);

type ProviderContextProviderProps = {
  children: React.ReactNode;
};
export const ProviderContextProvider = ({ children }: ProviderContextProviderProps) => {
  const [plan] = useState(defaultPlan);

  return (
    <ProviderContext.Provider
      value={{
        modelProviders: [],
        textGenerationModelList: [],
        isAPIKeySet: true,
        supportRetrievalMethods: [],
        plan,
        isFetchedPlan: true,
        enableBilling: true,
        onPlanInfoChanged: () => {},
        enableReplaceWebAppLogo: false,
        modelLoadBalancingEnabled: false,
        datasetOperatorEnabled: false,
      }}
    >
      {children}
    </ProviderContext.Provider>
  );
};

export default ProviderContext;
